//
//  HEIMImageViewCell.m
//  HealthFamily
//
//  Created by 吴欧 on 2020/11/28.
//  Copyright © 2020 honglutec. All rights reserved.
//

#import "HEIMImageViewCell.h"
#import "HEIMImageItemCell.h"
#import "KNPhotoBrowser.h"

@interface HEIMImageViewCell ()<UICollectionViewDataSource, UICollectionViewDelegateFlowLayout, KNPhotoBrowserDelegate>

@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) UICollectionViewFlowLayout *layout;
@property (nonatomic, assign) BOOL hasLoad;
@property (nonatomic, strong) NSArray <HEDoctorInfoModel *> *showList;
@property (nonatomic, strong) NSMutableArray * itemsArr;
@property (nonatomic, strong) KNPhotoBrowser *photoBrowser;

@end
 
@implementation HEIMImageViewCell

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
    
    if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
        self.selectionStyle = UITableViewCellSelectionStyleNone;
        [self initUI];
    }
    return self;
}

- (void)initUI {
 
    
    // 1.创建流水布局
    _layout = [[UICollectionViewFlowLayout alloc] init];
    _layout.scrollDirection = UICollectionViewScrollDirectionVertical;
//    _layout.estimatedItemSize = CGSizeMake(120, 100);

    _collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:_layout];
    _collectionView.backgroundColor = UIColor.clearColor;
    _collectionView.dataSource = self;
    _collectionView.delegate = self;
    _collectionView.scrollEnabled = NO;
    _collectionView.showsHorizontalScrollIndicator = NO;
    [self.bubbleView addSubview:_collectionView];
    
    [_collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.bubbleView).mas_offset(10);
        make.left.equalTo(self.bubbleView).mas_offset(10);
        make.right.equalTo(self.bubbleView).mas_offset(-10);
        make.bottom.equalTo(self.bubbleView).mas_offset(-10);
    }];
    
    /// 设置此属性为yes 不满一屏幕 也能滚动
    self.collectionView.alwaysBounceHorizontal = YES;
    self.collectionView.showsHorizontalScrollIndicator = NO;
    [_collectionView registerClass:HEIMImageItemCell.class forCellWithReuseIdentifier: KHEIMImageItemCell];
}
 
- (void)configCellWithModel:(HEIMMessageModel *)model {
    self.model = model;
    
    [_collectionView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.width.mas_offset(self.model.contentWidth);
        make.height.mas_offset(self.model.contentHeight);
    }]; 
    [_collectionView reloadData];

    [self refreshData:model];
    [self setBrow];
}

- (void)setBrow {
    self.itemsArr = self.model.KNPhotoItems;
}

- (CGFloat)getHeight {
    [_collectionView reloadData];
    return self.layout.collectionViewContentSize.height;
}
 
//解决ios8上自动布局的问题

- (BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds{
    return YES;
}


#pragma mark - 代理方法 Delegate Methods
// 设置分区
 

// 每个分区上得元素个数
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    HEIMImageObject *image = (HEIMImageObject *)self.model.message.messageObject;
    return image.imageArray.count;
}

// 设置cell
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    HEIMImageObject *image = (HEIMImageObject *)self.model.message.messageObject;

    HEIMImageItemCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier: KHEIMImageItemCell forIndexPath:indexPath];
    cell.image = image.imageArray[indexPath.item];
    return cell;
}

// 设置cell大小 itemSize：可以给每一个cell指定不同的尺寸
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    return CGSizeMake(self.model.imageItemWidth, self.model.imageItemWidth);
}


// 设置UIcollectionView整体的内边距（这样item不贴边显示）
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
    // 上 左 下 右
    return UIEdgeInsetsMake(0, 0 , 0, 0);
}

// 设置minimumLineSpacing：cell上下之间最小的距离
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section {
    return 10;
}

// 设置minimumInteritemSpacing：cell左右之间最小的距离
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section {
    return 5;
}

// 选中cell的回调
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    [self bigImage: indexPath.item];
}
 


#pragma mark -
- (NSMutableArray *)itemsArr {
    if (!_itemsArr) {
        _itemsArr = [NSMutableArray array];
    }
    return _itemsArr;
}

- (void)bigImage:(NSInteger)item {
 
    KNPhotoBrowser *photoBrowser = [[KNPhotoBrowser alloc] init];
    photoBrowser.itemsArr = [self.itemsArr copy];
    photoBrowser.isNeedPageNumView = true;
    photoBrowser.isNeedRightTopBtn = true;
    photoBrowser.isNeedPictureLongPress = true;
    photoBrowser.isNeedPanGesture = true;
    photoBrowser.isNeedPrefetch = true;
    photoBrowser.isNeedAutoPlay = true;
    photoBrowser.currentIndex = item;
    photoBrowser.delegate = self;
    [photoBrowser present];
    
    _photoBrowser = photoBrowser;
}

/* photoBrowser 右上角按钮的点击 */
- (void)photoBrowserRightOperationAction{
    
    __weak typeof(self) weakself = self;
    KNActionSheet *actionSheet = [[KNActionSheet share] initWithTitle:@"" cancelTitle:@"" titleArray:@[@"识别图中二维码",@"保存到相册"].mutableCopy destructiveArray:@[] actionSheetBlock:^(NSInteger buttonIndex) {
        if (buttonIndex == 0) {
            [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeClear];
            [SVProgressHUD show];
            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0) , ^{
                CIDetector *detector = [CIDetector detectorOfType:CIDetectorTypeQRCode context:nil options:@{CIDetectorAccuracy : CIDetectorAccuracyHigh}];
                dispatch_async(dispatch_get_main_queue(), ^{
                    UIImageView *imgView = [UIImageView new];
                    [imgView sd_setImageWithURL:[NSURL URLWithString:weakself.photoBrowser.itemsArr[weakself.photoBrowser.currentIndex].url] completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
                      
                            NSArray *features = [detector featuresInImage:[CIImage imageWithCGImage: image.CGImage]];
                            [SVProgressHUD dismiss];

                            if (features.count) {
                                [weakself.photoBrowser dismiss];

                                CIQRCodeFeature *feature = features.firstObject;
                                NSString *scannedResult = feature.messageString;
                                
                                NSURL * file = [NSURL URLWithString: scannedResult];
                                RootWebViewController *webView = [[RootWebViewController alloc] initWithUrl:file.absoluteString];
                                webView.isShowCloseBtn = YES;
                                webView.showPageTitle = YES;
                                [((UIViewController *)weakself.delegate).navigationController pushViewController:webView animated:YES];
                            }else {
                                [Dialog toastBottom:@"未识别到二维码!"];
                            }
                    }];
                });
            });
        }
        else if (buttonIndex == 1) {
            [weakself toSaveImage:[NSURL URLWithString:weakself.photoBrowser.itemsArr[weakself.photoBrowser.currentIndex].url]];
        }
    }];
    
    [actionSheet show];
}

/// long press
/// @param photoBrowser pb
/// @param longPress press
- (void)photoBrowser:(KNPhotoBrowser *)photoBrowser longPress:(UILongPressGestureRecognizer *)longPress {
    if (longPress.state == UIGestureRecognizerStateBegan) {
        [photoBrowser setImmediatelyPlayerRate:2];
    }else if (longPress.state == UIGestureRecognizerStateEnded || longPress.state == UIGestureRecognizerStateCancelled || longPress.state == UIGestureRecognizerStateFailed || longPress.state == UIGestureRecognizerStateRecognized){
        [photoBrowser setImmediatelyPlayerRate:1];
    }
}


- (void)toSaveImage:(NSURL *)url {
 
    SDWebImageManager *manager = [SDWebImageManager sharedManager];
    
    if ([manager cacheKeyForURL:url]) {
       [[manager imageCache] queryImageForKey:url.absoluteString options:SDWebImageFromCacheOnly context:nil completion:^(UIImage * _Nullable image, NSData * _Nullable data, SDImageCacheType cacheType) {
           // 保存图片到相册中
           UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
        }];
        return;
    }
    else {
        //从网络下载图片
        NSData *data = [NSData dataWithContentsOfURL:url];
        UIImage *img = [UIImage imageWithData:data];
        // 保存图片到相册中
        UIImageWriteToSavedPhotosAlbum(img,self, @selector(image:didFinishSavingWithError:contextInfo:),nil);
    }
}
//保存图片完成之后的回调
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error
  contextInfo:(void *)contextInfo {
    if (error != NULL) {
        [Dialog toast:@"图片保存失败" delay:2.0];
    }
    else  // No errors
    {
        [Dialog toast:@"图片保存成功" delay:2.0];
    }
}

@end
